<template>
  <el-dialog v-bind="dialog" :visible.sync="dialog.visible" class="role-dialog" @open="dialogOpen">
    <el-form v-bind="form" label-position="top" size="small">
      <el-form-item prop="name" label="角色名称:">
        <el-input v-model="form.model.name" />
      </el-form-item>
      <el-form-item prop="description" label="角色描述:">
        <el-input v-model="form.model.description" autosize type="textarea" resize="none" />
      </el-form-item>
    </el-form>
    <el-button slot="footer" size="small" type="primary" @click="submit">确 认</el-button>
  </el-dialog>
</template>

<script>
import { internetApi } from '@/api/api'

export default {
  props: {
    tableUpdate: Function
  },
  data() {
    return {
      //弹窗相关的属性
      dialog: {
        visible: false,
        title: '新建角色',
        width: '90%',
        closeOnClickModal: false
      },
      //form表单相关的参数
      form: {
        ref: 'form',
        model: {
          id: null,
          name: null,
          description: null
        },
        labelWidth: '90px',
        size: 'small',
        rules: {
          name: [
            { required: true, message: '角色名称不能为空', trigger: 'blur' },
            { min: 2, max: 8, message: '2-8个字之间', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '系统简介不能为空', trigger: 'blur' },
            { max: 100, message: '不超过100个字', trigger: 'blur' }
          ]
        }
      }
    }
  },

  methods: {
    //确认按钮
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.form.model.id) {
            await this.$request(internetApi.updateRole, this.form.model)
          } else {
            await this.$request(internetApi.addRole, this.form.model)
          }
          this.tableUpdate(1)
          this.dialog.visible = false
        }
      })
    },
    open(row) {
      if (row) {
        //编辑
        this.dialog.title = '编辑角色'
        this.form.model.id = row.id
        this.form.model.name = row.name
        this.form.model.description = row.description
      } else {
        //新增
        this.dialog.title = '新建角色'
        this.form.model.id = null
        this.form.model.name = null
        this.form.model.description = null
      }
      this.dialog.visible = true
    },
    //弹窗打开时，清除所有校验
    dialogOpen() {
      //dialog是懒加载，所以要用$nextTick
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper ::v-deep.el-dialog {
  max-width: 365px;
}

::v-deep.role-dialog .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 8px;
}

::v-deep.role-dialog .el-form--label-top .el-form-item__label {
  padding: 0 0 5px;
}

::v-deep.role-dialog .el-dialog__body {
  padding-top: 0;
  padding-bottom: 0;
}
</style>
